package com.lyf.task;

import com.lyf.mapper.admin.OrderMapper;
import com.lyf.pojo.Orders;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.Schedules;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 定时任务类：定时处理订单
 */
@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理付款超时订单
     * 每2分钟执行一次
     */
    @Scheduled(cron = "0 0/2 * * * ? ") // 每2分钟执行一次
    public void processTimeOutOrder () {
        log.info("处理超时订单");
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        // 查询超时订单，状态为待付款
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTime(Orders.PENDING_PAYMENT, time);

        // 处理超时订单，修改状态为已取消
        if (ordersList != null && ordersList.size() > 0) {
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.CANCELLED_ORDER);
                orders.setCancelReason("订单超时，自动取消");
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.update(orders);
            }
        }
    }

    /**
     * 处理派送超时订单
     * 每1小时执行一次
     */
    @Scheduled(cron = "0 0 1 * * ? ")  // 每天凌晨1点执行一次
    public void processDeliveryTimeOutOrder () {
        log.info("处理派送超时订单");
        // 查询派送超时订单，状态为派送中
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTime(Orders.TOBEDELIVERED, time);

        // 处理派送超时订单，修改状态为已完成
        if (ordersList != null && ordersList.size() > 0) {
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.COMPLETE_ORDER);
                orders.setDeliveryTime(LocalDateTime.now());
                orderMapper.update(orders);
            }
        }
    }
}
